package com.jack.leetcode.每日一题;

import java.util.ArrayDeque;
import java.util.Queue;

/***
 * BFS
 * @author zhangjie
 * @date 2020/3/29 19:51
 */
public class 地图分析 {

    public static void main(String[] args) {
        int [][] grid = {
                {1,0,1},
                {0,0,0},
                {1,0,1}
        };
        System.out.println(maxDistance(grid));
    }

    public static int maxDistance(int[][] grid) {
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        Queue<int[]> queue = new ArrayDeque<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                }
            }
        }

        int n = grid.length;
        boolean hasOcean = false;
        int[] point = null;
        while (!queue.isEmpty()) {
            point = queue.poll();
            for (int i = 0; i < 4; i++) {
                int x = point[0] + dx[i];
                int y = point[1] + dy[i];
                if (x < 0 || x >= n || y < 0 || y >= n || grid[x][y] != 0) {
                    continue;
                }
                hasOcean = true;
                queue.offer(new int[]{x, y});
                grid[x][y] = grid[point[0]][point[1]] + 1;
            }
        }
        if(point == null || !hasOcean){
            return -1;
        }
        return grid[point[0]][point[1]] - 1;
    }

}
